import { defineStore } from 'pinia'
import { store } from '../index'
import router from '@/router'
import guid from '@/utils/guid'

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            // 账号
            userName: localStorage.getItem('userName') || '',
            // 密码
            password: '',
            // 用户token
            token: sessionStorage.getItem('token') || '',
            // 用户信息
            userInfo: {},

        }
    },
    getters: {
        getUserName() {
            return this.userName
        },
        getUserInfo() {
            return this.userInfo
        }
    },
    actions: {
        // 登录
        login(userName, password) {
            if (userName === password) {
                console.log(userName, password)
                this.userName = userName
                this.password = password
                localStorage.setItem('userName', userName)
                sessionStorage.setItem('token', guid())
                router.push('/home')
            }
        },
        // 退出登录
        logoutConfirm() {
            console.log('退出登录')
            ElMessageBox.confirm('是否退出本系统？', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    sessionStorage.removeItem('token')
                    this.userInfo = null
                    router.replace('/login')
                    location.reload()
                })
                .catch(() => { })

        }
    },
    persist: true
})


export const useUserStoreWithOut = () => {
    return useUserStore(store)
}